package itu.twitterandro.application;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateStatusActivity extends Activity implements OnClickListener {

	static final String TAG = "MyTwitter";
	private final Integer tweetLength = 140;

	Button buttonUpdate;
	EditText textStatus;
	Context context;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sendtweet);

		final TextView tvChar = (TextView) this.findViewById(R.id.tvChar);
		// find views by id
		buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
		textStatus = (EditText) findViewById(R.id.textStatus);
		context = getApplicationContext();

		// Add listener
		buttonUpdate.setOnClickListener(this);

		textStatus.setOnKeyListener(new View.OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				Integer length = tweetLength - textStatus.getText().length();
				tvChar.setText(length.toString());
				return false;
			}
		});

	}

	public void onClick(View v) {
		String myStatus = textStatus.getText().toString();

		if (myStatus.length() == 0) {
			Toast.makeText(UpdateStatusActivity.this, "please write a tweet",
					Toast.LENGTH_LONG).show();
			return;
		}

		SharedPreferences settings = getSharedPreferences(
				TwitterKeys.PREFS_NAME, MODE_PRIVATE);
		String accessTokenToken = settings.getString("accessTokenToken", null);
		String accessTokenSecret = settings
				.getString("accessTokenSecret", null);
		if (accessTokenToken == null || accessTokenSecret == null) {
			// access token is null
			Toast.makeText(UpdateStatusActivity.this, "please relogin",
					Toast.LENGTH_LONG).show();
			Intent loginIntent = new Intent(UpdateStatusActivity.this,
					AuthActivity.class);
			startActivity(loginIntent);
		} else {
			// access token exists
			Toast.makeText(UpdateStatusActivity.this, "sending ...",
				Toast.LENGTH_LONG).show();

			Twitter preAuthorizedTwitter = ((TwitterApplication) getApplication())
					.getTwitter();

			try {
				preAuthorizedTwitter.updateStatus(myStatus);
			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Toast.makeText(UpdateStatusActivity.this, "sending",
					Toast.LENGTH_LONG);
			Intent returnIntent = new Intent(UpdateStatusActivity.this,
					TwitterAndroActivity.class);
			startActivity(returnIntent);
		}

	}

}
